<?php
namespace backend\modules\wxsource\models;

use Yii;

class WxSourceData {
    /** @var \callmez\wechat\sdk\MpWechat $MpWechat  */
    public $MpWechat;

    public function __construct()
    {
        /** @var \callmez\wechat\sdk\MpWechat $MpWechat */
        $this->MpWechat = Yii::$app->MpWechat;
    }

    public function getSource()
    {
        $wxSourceARR = WxSource::find()->orderBy(['update_time'=>SORT_DESC])->limit(10)->all();
        if(!$wxSourceARR) {
            $data = [
                'type'=>'news',
                "offset"=>0,
                "count"=>20,
            ];
            $matList = $this->MpWechat->getMaterialList($data);

            $arrSourceARR  =  array();
            foreach($matList['item'] as $k=>$v) {
                $v['content']['news_item'][0]['media_id'] = $v['media_id'];
                $v['content']['news_item'][0]['update_time'] = $v['update_time'];
                $arrSourceARR[] = $v['content']['news_item'][0];
            }
            $model = new WxSource();
            foreach($arrSourceARR as $attributes)
            {
                $model->isNewRecord = true;
                $model->setAttributes($attributes);
                $model->save();
            }
            return $arrSourceARR;
        } else {
            return $wxSourceARR;
        }
    }
}
